// Package sys
// @Link  https://github.com/bufanyun/hotgo
// @Copyright  Copyright (c) 2025 HotGo CLI
// @Author  Ms <133814250@qq.com>
// @License  https://github.com/bufanyun/hotgo/blob/master/LICENSE
// @AutoGenerate Version 2.15.11
package sys

import (
	"context"
	"github.com/gogf/gf/v2/util/gconv"
	"hotgo/internal/dao"
	"hotgo/internal/library/contexts"
	"hotgo/internal/library/hgorm"
	"hotgo/internal/library/hgorm/handler"
	"hotgo/internal/model/input/sysin"
	"hotgo/internal/service"

	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
)

type sSysReceiverAddress struct{}

func NewSysReceiverAddress() *sSysReceiverAddress {
	return &sSysReceiverAddress{}
}

func init() {
	service.RegisterSysReceiverAddress(NewSysReceiverAddress())
}

// Model 收货地址ORM模型
func (s *sSysReceiverAddress) Model(ctx context.Context, option ...*handler.Option) *gdb.Model {
	return handler.Model(dao.ReceiverAddress.Ctx(ctx), option...)
}

// List 获取收货地址列表
func (s *sSysReceiverAddress) List(ctx context.Context, in *sysin.ReceiverAddressListInp) (list []*sysin.ReceiverAddressListModel, totalCount int, err error) {
	mod := s.Model(ctx, &handler.Option{FilterAuth: false})

	// 字段过滤
	mod = mod.FieldsPrefix(dao.ReceiverAddress.Table(), sysin.ReceiverAddressListModel{})
	mod = mod.Fields(hgorm.JoinFields(ctx, sysin.ReceiverAddressListModel{}, &dao.AdminMember, "adminMember"))

	// 关联表字段
	mod = mod.LeftJoinOnFields(dao.AdminMember.Table(), dao.ReceiverAddress.Columns().MemberId, "=", dao.AdminMember.Columns().Id)

	// 查询主键ID
	if in.Id > 0 {
		mod = mod.Where(dao.ReceiverAddress.Columns().Id, in.Id)
	}

	// 查询收货人姓名
	if in.UserName != "" {
		mod = mod.WhereLike(dao.ReceiverAddress.Columns().UserName, in.UserName)
	}

	// 查询收货人手机号码
	if in.TelNumber != "" {
		mod = mod.WhereLike(dao.ReceiverAddress.Columns().TelNumber, in.TelNumber)
	}

	// 查询创建时间
	if len(in.CreatedAt) == 2 {
		mod = mod.WhereBetween(dao.ReceiverAddress.Columns().CreatedAt, in.CreatedAt[0], in.CreatedAt[1])
	}

	// 查询管理员ID
	if in.AdminMemberId > 0 {
		mod = mod.WherePrefix(dao.AdminMember.Table(), dao.AdminMember.Columns().Id, in.AdminMemberId)
	}

	// 查询微信昵称
	if in.AdminMemberNickname != "" {
		mod = mod.WherePrefixLike(dao.AdminMember.Table(), dao.AdminMember.Columns().Nickname, "%"+in.AdminMemberNickname+"%")
	}

	//

	// 分页
	mod = mod.Page(in.Page, in.PerPage)

	// 排序
	mod = mod.OrderDesc(dao.ReceiverAddress.Table() + "." + dao.ReceiverAddress.Columns().Id)

	// 查询数据
	if err = mod.ScanAndCount(&list, &totalCount, false); err != nil {
		err = gerror.Wrap(err, "获取收货地址列表失败，请稍后重试！")
		return
	}
	return
}

// Edit 修改/新增收货地址
func (s *sSysReceiverAddress) Edit(ctx context.Context, in *sysin.ReceiverAddressEditInp, isUser bool) (err error) {
	return g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) (err error) {

		// 修改
		if in.Id > 0 {
			if isUser {
				flag, err2 := s.Model(ctx).WherePri(in.Id).Where(dao.ReceiverAddress.Columns().MemberId, contexts.GetUserId(ctx)).Exist()
				if err2 != nil {
					return gerror.Wrap(err2, "修改收货地址失败，请稍后重试！")
				}
				if !flag {
					return gerror.New("修改收货地址失败，请稍后重试！")
				}
			}
			if _, err = s.Model(ctx).
				Fields(sysin.ReceiverAddressUpdateFields{}).
				WherePri(in.Id).Data(in).Update(); err != nil {
				err = gerror.Wrap(err, "修改收货地址失败，请稍后重试！")
			}
			return
		}

		// 新增
		if isUser {
			in.MemberId = contexts.GetUserId(ctx)
			if in.PostalCode == "" && in.ProvinceName != "" && in.CityName != "" && in.CountyName != "" {
				data, _ := service.SysProvinces().GetCityByName(ctx, &sysin.ProvincesGetCityByNameInp{
					Title1: in.ProvinceName,
					Title2: in.CityName,
					Title3: in.CountyName,
				})
				if data != nil {
					in.PostalCode = gconv.String(data.Id)
				}
			}
		}
		if _, err = s.Model(ctx, &handler.Option{FilterAuth: false}).
			Fields(sysin.ReceiverAddressInsertFields{}).
			Data(in).OmitEmptyData().Insert(); err != nil {
			err = gerror.Wrap(err, "新增收货地址失败，请稍后重试！")
		}
		return
	})
}

// Delete 删除收货地址
func (s *sSysReceiverAddress) Delete(ctx context.Context, in *sysin.ReceiverAddressDeleteInp, isUser bool) (err error) {
	if isUser {
		flag, err2 := s.Model(ctx).WherePri(in.Id).Where(dao.ReceiverAddress.Columns().MemberId, contexts.GetUserId(ctx)).Exist()
		if err2 != nil {
			return gerror.Wrap(err2, "删除收货地址失败，请稍后重试！")
		}
		if !flag {
			return gerror.New("删除收货地址失败，请稍后重试！")
		}
	}
	if _, err = s.Model(ctx).WherePri(in.Id).Unscoped().Delete(); err != nil {
		err = gerror.Wrap(err, "删除收货地址失败，请稍后重试！")
		return
	}
	return
}

// View 获取收货地址指定信息
func (s *sSysReceiverAddress) View(ctx context.Context, in *sysin.ReceiverAddressViewInp) (res *sysin.ReceiverAddressViewModel, err error) {
	if err = s.Model(ctx).WherePri(in.Id).Scan(&res); err != nil {
		err = gerror.Wrap(err, "获取收货地址信息，请稍后重试！")
		return
	}
	return
}
